﻿using Edu.Http.Extensions;
using Edu.Http.Proxy;
using Infrastructure.Config.Core.External;
using Infrastructure.ExternalService.Core.CommonResources;
using Infrastructure.ExternalService.Core.Requests;
using Infrastructure.ExternalService.Core.Responses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace Infrastructure.ExternalService.Core.Imp.Extensions
{
    public class CommonResourcesClient : BaseHttpClient, ICommonResourcesClient
    {
        readonly OrderCenterApiOptions _orderingOptions;
        private readonly string formUrlencoded = "application/x-www-form-urlencoded";
        private readonly ILogger<CommonResourcesClient> _logger;

        public CommonResourcesClient(IOptions<OrderCenterApiOptions> options,
            HttpClient client, ILoggerFactory loggerFactory, ILogger<CommonResourcesClient> logger)
            : base(client, loggerFactory, options.Value.CommonResourcesOptions.EndPoint)
        {
            _orderingOptions = options.Value ?? throw new HttpProxyException($"{nameof(CommonResourcesClient)}配置获取失败");
            loggerFactory.CreateLogger<CommonResourcesClient>();
            _logger = logger;
        }


        /// <summary>
        /// 获取公司主体列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<CompanyResponse>> GetCompanyList(GetCompanyRequest request)
        {
            try
            {
                var formStr = ConvertRequestToCommonFormUrlEncode(request);
                var response = await PostJsonAsync<WrapResponse<List<CompanyResponse>>>(url: _orderingOptions.CommonResourcesOptions.GetCompanyList, jsonStr: formStr, formUrlencoded, headers: null);

                if (response != null && response.Success && response.Data != null)
                {
                    return response.Data;
                }

                _logger.LogError(@$"获取公司主体列表错误。Message:{response.Msg}");
            }
            catch (System.Exception ex)
            {
                _logger.LogError(@$"获取公司主体列表异常。Message:{ex.Message};StackTrac:{ex.StackTrace}");
            }
            return new List<CompanyResponse>();
        }
    }
}